import type { UserInfo } from "@/pages/login/apis/type"
import { getTokenValue, removeTokenName, removeTokenValue, setTokenName, setTokenValue } from "@@/utils/cache/cookies"
import { getUserInfoLS, removeUserInfoLS, setUserInfoLS } from "@/common/utils/cache/local-storage"
import { logoutApi } from "@/pages/login/apis"
import { pinia } from "@/pinia"
import { resetRouter } from "@/router"
import { useSettingsStore } from "./settings"
import { useTagsViewStore } from "./tags-view"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getTokenValue() || "")

  const userInfo = ref<UserInfo | undefined>(getUserInfoLS<UserInfo>() ?? undefined)

  const roles = ref<string[]>([])

  const username = ref<string>("")

  const tagsViewStore = useTagsViewStore()

  const settingsStore = useSettingsStore()

  const setTokenInfo = (name: string, value: string) => {
    setTokenName(name)
    setTokenValue(value)
    token.value = value
  }

  // 一次性设置用户信息（登录后的 data）
  const setUserInfo = (value: UserInfo) => {
    const minimal = {
      userId: value.userId,
      username: value.username,
      realName: value.realName
    } as UserInfo
    userInfo.value = minimal
    setUserInfoLS(minimal)
    username.value = value.realName
    setTokenInfo(value.tokenName, value.tokenValue)
  }

  // 模拟角色变化
  const changeRoles = (role: string) => {
    const newToken = `token-${role}`
    token.value = newToken
    setTokenValue(newToken)
    // 用刷新页面代替重新登录
    location.reload()
  }

  // 登出
  const logout = async () => {
    logoutApi()
    removeTokenValue()
    removeTokenName()
    token.value = ""
    roles.value = []
    resetRouter()
    resetTagsView()
    removeUserInfoLS()
  }

  // 重置 Token
  const resetToken = () => {
    removeTokenValue()
    removeTokenName()
    token.value = ""
    roles.value = []
    removeUserInfoLS()
  }

  // 重置 Visited Views 和 Cached Views
  const resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  return { token, roles, username, userInfo, setTokenInfo, setUserInfo, changeRoles, logout, resetToken }
})

/**
 * @description 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * @description 在 SSR 应用中可用于在 setup 外使用 store
 */
export function useUserStoreOutside() {
  return useUserStore(pinia)
}
